import React from 'react';
import { View, Text, TouchableOpacity, StyleSheet } from 'react-native';
import { connect } from 'react-redux';
import * as loginAction from './LoginAction';
import { NavigationActions, StackActions } from 'react-navigation';
import UserDao from "../UserDao";
import NavigationUtil from "../../../global/navigator/NavigationUtil";

class LoginScreen extends React.Component {

  static navigationOptions = {
    headerTitle: '登录'
  };

  shouldComponentUpdate(nextProps, nextState) {//接收 Props的变化。如果变化为isSuccess =true则跳转
    if (nextProps.isSuccess) {
      setTimeout(() => {
        NavigationUtil.resetTo(this.props, "Main");
      }, 500)
      return true;//如果是false,则"登录中..."这个textview不会刷新 因为shouldComponentUpdate返回了false
    }
    return true;
  }

  render() {
    const { login, isSuccess, loading } = this.props;
    return (
      <View style={styles.container}>
        <TouchableOpacity style={styles.loginButton} activeOpacity={0.7} onPress={() => login()}>
          <Text style={styles.buttonText}>登录</Text>
        </TouchableOpacity >
        <Text style={{ marginTop: 10 }}>
          {loading ? "登录中..." : (isSuccess ? "登录成功" : "未登录")/*这里可以接收到登录的状态*/}
        </Text >
      </View >
    )
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center'
  },
  loginButton: {
    width: 150,
    height: 40,
    borderRadius: 4,
    backgroundColor: '#4ca5ff',
    alignItems: 'center',
    justifyContent: 'center'
  },
  buttonText: {
    fontSize: 17,
    fontWeight: 'bold',
    color: 'white'
  }
});

export default connect(
  (state) => ({
    errorMessage: state.loginIn.errorMessage,//reducer 处理完数据后可以在这里设置到props中
    isSuccess: state.loginIn.isSuccess,
    user: state.loginIn.user,
    loading: state.loginIn.loading
  }),
  (dispatch) => ({
    login: () => dispatch(loginAction.login())//connect后可以从props中获取这个方法的指针
  })
)(LoginScreen)